package com.richard.room.app;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.AutoMigration;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.TypeConverters;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.richard.library.basic.util.ThreadUtil;
import com.richard.room.app.entity.Book;
import com.richard.room.app.entity.Device;
import com.richard.room.app.entity.Goods;
import com.richard.room.app.entity.Phone;
import com.richard.room.app.entity.User;
import com.richard.room.operator.api.Entity;
import com.richard.room.operator.api.EntityManager;
import com.richard.room.operator.api.RoomOperator;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author: Richard
 * @createDate: 2023/8/8 14:29
 * @version: 1.0
 * @description: 描述
 */
@Database(entities = {User.class, Book.class, Device.class, Phone.class, Goods.class}
        , exportSchema = true
        , version = 3
        , autoMigrations = {@AutoMigration(from = 1, to = 2), @AutoMigration(from = 2, to = 3)}
)
@TypeConverters(DataConverter.class)
public abstract class DB extends RoomOperator {

    private static DB db;

    /**
     * 初始化数据库
     */
    public static void init(Context context) {
        if (db == null) {
            db = Room.databaseBuilder(context, DB.class, "test.db")
                    .allowMainThreadQueries()//能避免主线程操作DB，一定要在子线程操作
                    .setQueryExecutor(ThreadUtil.getIoPool(1))//读线程池
                    .setTransactionExecutor(ThreadUtil.getSinglePool(2))//写队列
                    //.enableMultiInstanceInvalidation()//多进程需开启
                    //.setJournalMode(JournalMode.WRITE_AHEAD_LOGGING)//写操作不阻塞读操作
                    .build();

            RoomOperator.setCursorWindowSize(4 * 1024 * 1024);
        }
    }

    public static DB get() {
        return db;
    }

    @Override
    public <T> Entity<T> getEntity(Class<T> entityClass) {
        return EntityManager.getEntity(entityClass);
    }

    public abstract TestDao testDao();

}
